<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadRequestOptions,
  CascaderOption
} from "element-plus";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";
import {
  fetchCompanyVerification,
  saveCompanyVerification,
  saveCompanyInvoice,
  saveCompanyAddresses,
  recognizeBusinessLicense,
  fetchVerificationRegions,
  fetchGeoRegions,
  type CompanyVerificationInfo,
  type CompanyInvoiceInfo,
  type CompanyAddressInfo,
  type RegionTreeNode
} from "@/api/verification";
import { getPartialStatus } from "@/api/user";
import { getToken } from "@/utils/auth";
import { uploadFile } from "@/utils/upload";

const router = useRouter();
const userStore = useUserStoreHook();

const loading = ref(false);
const stepSubmitting = reactive({
  company: false,
  invoice: false,
  address: false
});
const uploading = ref(false);
const uploadProgress = ref(0);
const activeStep = ref(0);
const status = ref<number | null>(null);
const ocrRaw = ref<Record<string, any> | null>(null);

const companyFormRef = ref<FormInstance>();
const invoiceFormRef = ref<FormInstance>();
const shippingFormRef = ref<FormInstance>();
const billingFormRef = ref<FormInstance>();

const companyForm = reactive({
  company_name: "",
  license_code: "",
  license_photo: "",
  legal_rep: "",
  address: "",
  scope: "",
  region_path: [] as number[],
  region_id: null as number | null
});

const defaultInvoice = (): CompanyInvoiceInfo => ({
  invoice_title: "",
  invoice_taxno: "",
  bank_name: "",
  bank_account: "",
  bank_account_name: "",
  contact_name: "",
  contact_phone: "",
  contact_email: ""
});

const invoiceForm = reactive<CompanyInvoiceInfo>(defaultInvoice());

type AddressForm = CompanyAddressInfo & {
  postal_code?: string;
  geo_path?: number[];
};

const createDefaultAddress = (type: "shipping" | "billing"): AddressForm => ({
  address_type: type,
  contact_name: "",
  contact_phone: "",
  province: "",
  city: "",
  district: "",
  address: "",
  postal_code: "",
  is_default: type === "shipping" ? 1 : 0,
  geo_path: []
});

const addressForms = reactive({
  shipping: createDefaultAddress("shipping"),
  billing: createDefaultAddress("billing")
});

const companyRules: FormRules = {
  company_name: [
    { required: true, message: "请输入企业名称", trigger: "blur" }
  ],
  license_code: [
    { required: true, message: "请输入统一社会信用代码", trigger: "blur" }
  ],
  legal_rep: [{ required: true, message: "请输入法定代表人", trigger: "blur" }],
  license_photo: [
    { required: true, message: "请上传营业执照照片", trigger: "change" }
  ],
  region_path: [
    { required: true, message: "请选择所属区域", trigger: "change" }
  ]
};

const invoiceRules: FormRules = {
  invoice_title: [
    { required: true, message: "请输入开票抬头", trigger: "blur" }
  ],
  invoice_taxno: [
    { required: true, message: "请输入纳税人识别号", trigger: "blur" }
  ],
  contact_phone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" }
  ]
};

const addressRules: FormRules = {
  geo_path: [{ required: true, message: "请选择省市区", trigger: "change" }],
  contact_name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contact_phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" }
  ],
  address: [{ required: true, message: "请输入详细地址", trigger: "blur" }]
};

const sellerIdentity = computed(() =>
  (userStore.partialContext?.identities || []).find(
    (item: any) => item.type === "seller"
  )
);

const lastFetchedCompany = ref<CompanyVerificationInfo | null>(null);

const hasInvoiceInfo = computed(() => {
  const invoice = lastFetchedCompany.value?.invoice;
  return !!(invoice && invoice.invoice_title && invoice.invoice_taxno);
});

const hasAddressInfo = computed(() => {
  const addresses = lastFetchedCompany.value?.addresses;
  return Array.isArray(addresses) && addresses.length > 0;
});

const showPendingResult = computed(
  () => status.value === 0 && hasInvoiceInfo.value && hasAddressInfo.value
);

const statusDescription = computed(() => {
  switch (status.value) {
    case 0:
      return "资料已提交，正在审核中";
    case 1:
      return "企业认证已通过，可联系管理员开通权限";
    case 2:
      return "审核未通过，请核对信息后重新提交";
    default:
      return "请按步骤完善企业资料，以完成卖家端登录";
  }
});

const regionCascaderOptions = ref<CascaderOption[]>([]);
const regionMeta = new Map<
  number,
  { path: number[]; name: string; level: number }
>();

const geoRegionTree = ref<RegionTreeNode[]>([]);
const geoRegionOptions = ref<CascaderOption[]>([]);
const geoRegionMeta = new Map<
  string,
  { path: string[]; names: string[]; level: number }
>();
const shippingGeoPath = ref<string[]>([]);
const billingGeoPath = ref<string[]>([]);

const normalizeRegionOptions = (
  nodes: RegionTreeNode[],
  path: number[] = []
): CascaderOption[] =>
  nodes.map(node => {
    const id = Number(node.id);
    const currentPath = [...path, id];
    regionMeta.set(id, {
      path: currentPath,
      name: node.name,
      level: node.level ?? currentPath.length
    });
    return {
      value: id,
      label: node.name,
      children: node.children
        ? normalizeRegionOptions(node.children, currentPath)
        : undefined
    };
  });

const setRegionPathById = (regionId: number | null | undefined) => {
  if (!regionId) {
    companyForm.region_path = [];
    companyForm.region_id = null;
    return;
  }
  const meta = regionMeta.get(regionId);
  if (meta) {
    companyForm.region_path = [...meta.path];
    companyForm.region_id = meta.path[meta.path.length - 1] ?? null;
  }
};

const normalizeGeoOptions = (
  nodes: RegionTreeNode[],
  codePath: string[] = [],
  namePath: string[] = []
): CascaderOption[] =>
  nodes.map(node => {
    const code = String(node.code ?? node.id);
    const currentCodes = [...codePath, code];
    const currentNames = [...namePath, node.name];
    geoRegionMeta.set(code, {
      path: currentCodes,
      names: currentNames,
      level: node.level ?? currentCodes.length
    });
    const children = node.children
      ? normalizeGeoOptions(node.children, currentCodes, currentNames)
      : undefined;
    const option: CascaderOption = {
      value: code,
      label: node.name
    };
    if (children && children.length) {
      option.children = children;
    }
    return option;
  });

const resolveGeoPathFromNames = (address: CompanyAddressInfo): string[] => {
  const names = [address.province, address.city, address.district]
    .map(item => (item ?? "").trim())
    .filter(Boolean);
  if (names.length === 0) return [];

  const search = (nodes: RegionTreeNode[], depth: number): string[] | null => {
    if (!Array.isArray(nodes) || nodes.length === 0) {
      return null;
    }

    for (const node of nodes) {
      const code = String(node.code ?? node.id);
      if ((node.name ?? "") !== names[depth]) {
        continue;
      }

      if (depth === names.length - 1) {
        return [code];
      }

      if (node.children) {
        const result = search(node.children, depth + 1);
        if (result) {
          return [code, ...result];
        }
      }
    }

    return null;
  };

  const result = search(geoRegionTree.value, 0);
  return result ?? [];
};

watch(
  () => [...companyForm.region_path],
  path => {
    companyForm.region_id = path.length ? path[path.length - 1] : null;
  }
);

watch(
  shippingGeoPath,
  path => {
    if (!Array.isArray(path) || path.length === 0) {
      addressForms.shipping.geo_path = [];
      addressForms.shipping.province = "";
      addressForms.shipping.city = "";
      addressForms.shipping.district = "";
      return;
    }

    const lastCode = path[path.length - 1] ?? "";
    const meta = geoRegionMeta.get(lastCode);
    if (!meta) {
      return;
    }

    addressForms.shipping.province = meta.names[0] ?? "";
    addressForms.shipping.city = meta.names[1] ?? "";
    addressForms.shipping.district = meta.names[2] ?? "";
    addressForms.shipping.geo_path = [...path];
  },
  { deep: true }
);

watch(
  billingGeoPath,
  path => {
    if (!Array.isArray(path) || path.length === 0) {
      addressForms.billing.geo_path = [];
      addressForms.billing.province = "";
      addressForms.billing.city = "";
      addressForms.billing.district = "";
      return;
    }

    const lastCode = path[path.length - 1] ?? "";
    const meta = geoRegionMeta.get(lastCode);
    if (!meta) {
      return;
    }

    addressForms.billing.province = meta.names[0] ?? "";
    addressForms.billing.city = meta.names[1] ?? "";
    addressForms.billing.district = meta.names[2] ?? "";
    addressForms.billing.geo_path = [...path];
  },
  { deep: true }
);

const ensurePartialContext = () => {
  if (userStore.partialAction === "need_bind_phone") {
    router.replace("/welcome/bindphone");
    return false;
  }
  if (userStore.partialAction !== "need_verify_identity") {
    const token = getToken();
    if (token?.accessToken) {
      router.replace("/welcome");
    } else {
      router.replace("/login");
    }
    return false;
  }
  if (!userStore.partialToken) {
    message("认证流程已过期，请重新登录", { type: "warning" });
    router.replace("/login");
    return false;
  }
  return true;
};

const defaultInvoiceForm = () => {
  Object.assign(invoiceForm, defaultInvoice());
};

const applyInvoiceDefaults = () => {
  if (!invoiceForm.invoice_title && companyForm.company_name) {
    invoiceForm.invoice_title = companyForm.company_name;
  }
  if (!invoiceForm.invoice_taxno && companyForm.license_code) {
    invoiceForm.invoice_taxno = companyForm.license_code;
  }
};

const defaultAddressForms = () => {
  Object.assign(addressForms.shipping, createDefaultAddress("shipping"));
  Object.assign(addressForms.billing, createDefaultAddress("billing"));
  shippingGeoPath.value = [];
  billingGeoPath.value = [];
};

const assignAddresses = (addresses?: CompanyAddressInfo[] | null) => {
  defaultAddressForms();
  if (!Array.isArray(addresses)) return;
  const shipping = addresses.find(item => item.address_type === "shipping");
  const billing = addresses.find(item => item.address_type === "billing");
  if (shipping) {
    Object.assign(addressForms.shipping, shipping);
    shippingGeoPath.value = resolveGeoPathFromNames(shipping);
    addressForms.shipping.geo_path = [...shippingGeoPath.value];
  }
  if (billing) {
    Object.assign(addressForms.billing, billing);
    billingGeoPath.value = resolveGeoPathFromNames(billing);
    addressForms.billing.geo_path = [...billingGeoPath.value];
  }
};

const assignForm = (info?: CompanyVerificationInfo | null) => {
  if (!info) {
    defaultInvoiceForm();
    defaultAddressForms();
    lastFetchedCompany.value = null;
    return;
  }
  companyForm.company_name = info.company_name ?? "";
  companyForm.license_code = info.license_code ?? "";
  companyForm.license_photo = info.license_photo ?? "";
  companyForm.legal_rep = info.legal_rep ?? "";
  companyForm.address = info.address ?? "";
  companyForm.scope = info.scope ?? "";
  ocrRaw.value = info.raw ?? null;
  defaultInvoiceForm();
  if (info.invoice) {
    Object.assign(invoiceForm, info.invoice);
  }
  applyInvoiceDefaults();
  assignAddresses(info.addresses ?? []);
  if (info.region_id) {
    setRegionPathById(info.region_id);
  }
  lastFetchedCompany.value = info;
  if (companyForm.legal_rep && !addressForms.shipping.contact_name) {
    addressForms.shipping.contact_name = companyForm.legal_rep;
  }
  if (companyForm.address && !addressForms.shipping.address) {
    addressForms.shipping.address = companyForm.address;
  }
};

const hydrateFromContext = () => {
  const company = userStore.partialContext?.company as
    | CompanyVerificationInfo
    | undefined;
  if (company) {
    assignForm(company);
    status.value = company.status ?? null;
  }
};

const computeActiveStep = (info?: CompanyVerificationInfo | null): number => {
  if (!info) return 0;
  if (!info.license_code) return 0;
  if (!info.invoice) return 1;
  if (!info.addresses || info.addresses.length === 0) return 2;
  return 2;
};

const loadRegions = async () => {
  if (!userStore.partialToken) return;
  try {
    const res = await fetchVerificationRegions(userStore.partialToken);
    if (res.success) {
      regionMeta.clear();
      regionCascaderOptions.value = normalizeRegionOptions(res.data);
    }
    const geoRes = await fetchGeoRegions(userStore.partialToken);
    if (geoRes.success) {
      geoRegionTree.value = geoRes.data;
      geoRegionMeta.clear();
      geoRegionOptions.value = normalizeGeoOptions(geoRes.data);
    }
  } catch (error: any) {
    const msg = error?.message ?? "加载区域信息失败";
    message(msg, { type: "warning" });
  }
};

const setCompanyRegionIfMissing = () => {
  if (!companyForm.region_id && companyForm.address) {
    suggestRegionFromAddress(companyForm.address);
  }
};

const suggestRegionFromAddress = (address: string) => {
  if (!address || regionMeta.size === 0) return;
  const normalized = address.replace(/\s+/g, "");
  let candidate: { path: number[]; name: string; level: number } | null = null;
  regionMeta.forEach(meta => {
    if (normalized.includes(meta.name)) {
      if (!candidate || meta.level > candidate.level) {
        candidate = meta;
      }
    }
  });
  if (candidate) {
    companyForm.region_path = [...candidate.path];
    companyForm.region_id = candidate.path[candidate.path.length - 1] ?? null;
  }
};

const loadVerification = async () => {
  if (!ensurePartialContext()) return;
  loading.value = true;
  try {
    hydrateFromContext();
    const partial = await getPartialStatus(userStore.partialToken!);
    if (partial.success && partial.data) {
      userStore.updatePartialContext(partial.data.context, true);
      userStore.updatePartialContext({
        identities: partial.data.identities,
        company: partial.data.company
      });
    }
    const res = await fetchCompanyVerification(userStore.partialToken!);
    if (res.success && res.data) {
      assignForm(res.data.company ?? null);
      status.value = res.data.company?.status ?? null;
      userStore.updatePartialContext({
        ...(userStore.partialContext ?? {}),
        identities: res.data.identities,
        company: res.data.company
      });
      activeStep.value = computeActiveStep(res.data.company);
      setCompanyRegionIfMissing();
    }
  } catch (error: any) {
    const msg = error?.message ?? "加载认证信息失败";
    message(msg, { type: "error" });
  } finally {
    loading.value = false;
  }
};

const submitCompany = async () => {
  if (!companyFormRef.value) return;
  const valid = await companyFormRef.value.validate().catch(() => false);
  if (!valid) return;
  stepSubmitting.company = true;
  try {
    const payload = {
      company_name: companyForm.company_name,
      license_code: companyForm.license_code,
      license_photo: companyForm.license_photo,
      legal_rep: companyForm.legal_rep,
      address: companyForm.address,
      scope: companyForm.scope,
      region_id: companyForm.region_id,
      raw: ocrRaw.value
    } as CompanyVerificationInfo;
    const res = await saveCompanyVerification(userStore.partialToken!, payload);
    if (res.success && res.data) {
      assignForm(res.data.company ?? null);
      status.value = res.data.company?.status ?? null;
      userStore.updatePartialContext({
        ...(userStore.partialContext ?? {}),
        identities: res.data.identities,
        company: res.data.company
      });
      activeStep.value = 1;
      applyInvoiceDefaults();
      message("企业信息已保存", { type: "success" });
    }
  } catch (error: any) {
    const msg = error?.message ?? "提交失败";
    message(msg, { type: "error" });
  } finally {
    stepSubmitting.company = false;
  }
};

const submitInvoice = async () => {
  if (!invoiceFormRef.value) return;
  const valid = await invoiceFormRef.value.validate().catch(() => false);
  if (!valid) return;
  stepSubmitting.invoice = true;
  try {
    const res = await saveCompanyInvoice(userStore.partialToken!, invoiceForm);
    if (res.success && res.data) {
      assignForm(res.data.company ?? null);
      userStore.updatePartialContext({
        ...(userStore.partialContext ?? {}),
        identities: res.data.identities,
        company: res.data.company
      });
      activeStep.value = 2;
      message("开票信息已保存", { type: "success" });
    }
  } catch (error: any) {
    const msg = error?.message ?? "提交失败";
    message(msg, { type: "error" });
  } finally {
    stepSubmitting.invoice = false;
  }
};

const stripGeoPath = (address: AddressForm): CompanyAddressInfo => {
  const { geo_path, ...rest } = address;
  return { ...rest };
};

const collectAddressPayload = (): CompanyAddressInfo[] => [
  stripGeoPath(addressForms.shipping),
  stripGeoPath(addressForms.billing)
];

const submitAddresses = async () => {
  if (!shippingFormRef.value || !billingFormRef.value) return;
  const [shippingValid, billingValid] = await Promise.all([
    shippingFormRef.value.validate().catch(() => false),
    billingFormRef.value.validate().catch(() => false)
  ]);
  if (!shippingValid || !billingValid) return;
  stepSubmitting.address = true;
  try {
    const res = await saveCompanyAddresses(
      userStore.partialToken!,
      collectAddressPayload()
    );
    if (res.success && res.data) {
      assignForm(res.data.company ?? null);
      status.value = res.data.company?.status ?? null;
      userStore.updatePartialContext({
        ...(userStore.partialContext ?? {}),
        identities: res.data.identities,
        company: res.data.company
      });
      message("地址信息已保存", { type: "success" });
      if (status.value === 0) {
        // 进入审核中
        activeStep.value = 2;
      }
    }
  } catch (error: any) {
    const msg = error?.message ?? "提交失败";
    message(msg, { type: "error" });
  } finally {
    stepSubmitting.address = false;
  }
};

const autofillBusinessLicense = async (imageUrl: string) => {
  if (!userStore.partialToken) return;
  try {
    const res = await recognizeBusinessLicense(userStore.partialToken, {
      image_url: imageUrl
    });
    if (res.success && res.data) {
      const info = res.data;
      companyForm.company_name = info.company_name || companyForm.company_name;
      companyForm.license_code =
        info.business_license_number ||
        info.license_code ||
        companyForm.license_code;
      companyForm.legal_rep =
        info.legal_representative || companyForm.legal_rep || "";
      companyForm.address = info.company_address || companyForm.address || "";
      companyForm.scope =
        info.business_scope || info.scope || companyForm.scope || "";
      ocrRaw.value = info.raw ?? null;
      setCompanyRegionIfMissing();
      applyInvoiceDefaults();
      if (companyForm.legal_rep && !addressForms.shipping.contact_name) {
        addressForms.shipping.contact_name = companyForm.legal_rep;
      }
      if (companyForm.address && !addressForms.shipping.address) {
        addressForms.shipping.address = companyForm.address;
      }
      message("营业执照识别成功，已自动填写信息", { type: "success" });
    } else {
      message(res.msg || "营业执照识别失败，请手动填写信息", {
        type: "warning"
      });
    }
  } catch (error: any) {
    const msg = error?.message ?? "营业执照识别失败，请手动填写信息或稍后重试";
    message(msg, { type: "warning" });
  }
};

const handleLicenseUpload = (options: UploadRequestOptions) => {
  uploading.value = true;
  uploadProgress.value = 0;
  uploadFile(
    options,
    percent => {
      uploadProgress.value = percent;
    },
    async url => {
      companyForm.license_photo = url;
      uploading.value = false;
      uploadProgress.value = 100;
      message("营业执照上传成功", { type: "success" });
      companyFormRef.value?.clearValidate?.(["license_photo"]);
      await autofillBusinessLicense(url);
    },
    error => {
      uploading.value = false;
      uploadProgress.value = 0;
      message(error || "上传失败，请重试", { type: "error" });
    },
    { partialToken: userStore.partialToken ?? undefined }
  );
};

const beforeLicenseUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    message("仅支持上传图片格式的营业执照", { type: "warning" });
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message("营业执照图片大小不能超过 2MB", { type: "warning" });
    return false;
  }
  return true;
};

const removeLicensePhoto = () => {
  companyForm.license_photo = "";
  uploadProgress.value = 0;
};

const copyShippingToBilling = () => {
  const currentDefault = addressForms.billing.is_default ?? 0;
  Object.assign(addressForms.billing, {
    ...addressForms.shipping,
    address_type: "billing",
    is_default: currentDefault
  });
  billingGeoPath.value = [...shippingGeoPath.value];
  addressForms.billing.geo_path = [...billingGeoPath.value];
};

const backToLogin = () => {
  userStore.logOut();
};

watch(
  () => userStore.partialAction,
  action => {
    if (action === "need_bind_phone") {
      router.replace("/welcome/bindphone");
    }
  }
);

onMounted(async () => {
  if (!ensurePartialContext()) return;
  loading.value = true;
  await loadRegions();
  await loadVerification();
  setCompanyRegionIfMissing();
  loading.value = false;
});
</script>

<template>
  <div class="verify-wrapper">
    <el-card v-loading="loading" class="verify-card">
      <h2 class="title">企业认证</h2>
      <p class="subtitle">{{ statusDescription }}</p>

      <el-alert
        v-if="sellerIdentity"
        type="info"
        :closable="false"
        class="status-alert"
      >
        当前卖家身份状态：
        <strong>
          {{ sellerIdentity.status === 1 ? "已激活" : "待审核" }}
        </strong>
      </el-alert>

      <template v-if="showPendingResult">
        <el-result
          icon="info"
          title="审核中"
          sub-title="我们将在1-3个工作日内完成审核，请耐心等待。"
        >
          <template #extra>
            <el-button type="primary" plain @click="backToLogin">
              返回登录
            </el-button>
          </template>
        </el-result>
      </template>

      <template v-else-if="status === 1">
        <el-result
          icon="success"
          title="认证已通过"
          :sub-title="statusDescription"
        >
          <template #extra>
            <el-button type="primary" plain @click="backToLogin">
              返回登录
            </el-button>
          </template>
        </el-result>
      </template>

      <template v-else>
        <el-steps :active="activeStep" finish-status="success" align-center>
          <el-step title="企业主体信息" />
          <el-step title="开票信息" />
          <el-step title="地址信息" />
        </el-steps>

        <div v-show="activeStep === 0" class="step-content">
          <el-form
            ref="companyFormRef"
            :model="companyForm"
            :rules="companyRules"
            label-width="120px"
            class="form-block"
          >
            <el-form-item label="营业执照照片" prop="license_photo">
              <el-upload
                class="license-upload"
                action=""
                :http-request="handleLicenseUpload"
                :before-upload="beforeLicenseUpload"
                :show-file-list="false"
                :disabled="uploading"
                accept="image/*"
              >
                <template v-if="companyForm.license_photo">
                  <div class="license-preview">
                    <img :src="companyForm.license_photo" alt="营业执照" />
                    <div class="preview-actions">
                      <el-button
                        type="primary"
                        link
                        :disabled="uploading"
                        @click.stop="removeLicensePhoto"
                      >
                        重新上传
                      </el-button>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <div class="upload-drop">
                    <div class="upload-plus">+</div>
                    <p class="upload-tip">
                      点击上传营业执照，系统会自动识别信息
                    </p>
                  </div>
                </template>
              </el-upload>
              <div class="el-upload__tip">
                支持 jpg / png，大小不超过 2MB
                <span v-if="uploading && uploadProgress < 100">
                  （上传中 {{ uploadProgress }}%）
                </span>
              </div>
            </el-form-item>

            <el-form-item label="企业名称" prop="company_name">
              <el-input
                v-model="companyForm.company_name"
                placeholder="请输入企业名称"
              />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="license_code">
              <el-input
                v-model="companyForm.license_code"
                placeholder="请输入统一社会信用代码"
              />
            </el-form-item>
            <el-form-item label="法定代表人" prop="legal_rep">
              <el-input
                v-model="companyForm.legal_rep"
                placeholder="请输入法人姓名"
              />
            </el-form-item>
            <el-form-item label="注册地址">
              <el-input
                v-model="companyForm.address"
                placeholder="请输入注册地址"
              />
            </el-form-item>
            <el-form-item label="经营范围">
              <el-input
                v-model="companyForm.scope"
                type="textarea"
                :rows="4"
                placeholder="请输入主营业务或经营范围"
              />
            </el-form-item>
            <el-form-item label="所属区域" prop="region_path">
              <el-cascader
                v-model="companyForm.region_path"
                :options="regionCascaderOptions"
                :props="{
                  value: 'value',
                  label: 'label',
                  children: 'children'
                }"
                clearable
                filterable
                placeholder="请选择企业所属区域"
                style="width: 100%"
              />
            </el-form-item>

            <div class="form-actions">
              <el-button
                type="primary"
                :loading="stepSubmitting.company"
                @click="submitCompany"
              >
                保存并继续
              </el-button>
              <el-button link type="primary" @click="backToLogin">
                返回登录
              </el-button>
            </div>
          </el-form>
        </div>

        <div v-show="activeStep === 1" class="step-content">
          <el-form
            ref="invoiceFormRef"
            :model="invoiceForm"
            :rules="invoiceRules"
            label-width="120px"
            class="form-block"
          >
            <el-form-item label="开票抬头" prop="invoice_title">
              <el-input
                v-model="invoiceForm.invoice_title"
                placeholder="请输入开票抬头"
              />
            </el-form-item>
            <el-form-item label="纳税人识别号" prop="invoice_taxno">
              <el-input
                v-model="invoiceForm.invoice_taxno"
                placeholder="请输入纳税人识别号"
              />
            </el-form-item>
            <el-form-item label="开户银行">
              <el-input
                v-model="invoiceForm.bank_name"
                placeholder="请输入开户银行"
              />
            </el-form-item>
            <el-form-item label="银行账号">
              <el-input
                v-model="invoiceForm.bank_account"
                placeholder="请输入银行账号"
              />
            </el-form-item>
            <el-form-item label="开户名称">
              <el-input
                v-model="invoiceForm.bank_account_name"
                placeholder="请输入开户名称"
              />
            </el-form-item>
            <el-form-item label="联系人">
              <el-input
                v-model="invoiceForm.contact_name"
                placeholder="请输入联系人"
              />
            </el-form-item>
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input
                v-model="invoiceForm.contact_phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
            <el-form-item label="联系邮箱">
              <el-input
                v-model="invoiceForm.contact_email"
                placeholder="请输入联系邮箱"
              />
            </el-form-item>

            <div class="form-actions">
              <el-button @click="activeStep = 0">上一步</el-button>
              <el-button
                type="primary"
                :loading="stepSubmitting.invoice"
                @click="submitInvoice"
              >
                保存并继续
              </el-button>
              <el-button link type="primary" @click="backToLogin">
                返回登录
              </el-button>
            </div>
          </el-form>
        </div>

        <div v-show="activeStep === 2" class="step-content">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-card shadow="never" class="address-card">
                <template #header>
                  <div class="card-header">
                    <span>默认发货地址</span>
                  </div>
                </template>
                <el-form
                  ref="shippingFormRef"
                  :model="addressForms.shipping"
                  :rules="addressRules"
                  label-width="100px"
                >
                  <el-form-item label="联系人" prop="contact_name">
                    <el-input
                      v-model="addressForms.shipping.contact_name"
                      placeholder="请输入联系人"
                    />
                  </el-form-item>
                  <el-form-item label="联系电话" prop="contact_phone">
                    <el-input
                      v-model="addressForms.shipping.contact_phone"
                      placeholder="请输入联系电话"
                    />
                  </el-form-item>
                  <el-form-item label="省市区" prop="geo_path">
                    <el-cascader
                      v-model="shippingGeoPath"
                      :options="geoRegionOptions"
                      :props="{
                        value: 'value',
                        label: 'label',
                        children: 'children'
                      }"
                      filterable
                      placeholder="请选择省市区"
                      style="width: 100%"
                    />
                  </el-form-item>
                  <el-form-item label="详细地址" prop="address">
                    <el-input
                      v-model="addressForms.shipping.address"
                      type="textarea"
                      :rows="2"
                      placeholder="请输入详细地址"
                    />
                  </el-form-item>
                  <el-form-item label="邮编">
                    <el-input
                      v-model="addressForms.shipping.postal_code"
                      placeholder="请输入邮编"
                    />
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="address-card">
                <template #header>
                  <div class="card-header">
                    <span>默认收货地址</span>
                    <el-button
                      type="primary"
                      link
                      @click="copyShippingToBilling"
                    >
                      同发货地址
                    </el-button>
                  </div>
                </template>
                <el-form
                  ref="billingFormRef"
                  :model="addressForms.billing"
                  :rules="addressRules"
                  label-width="100px"
                >
                  <el-form-item label="联系人" prop="contact_name">
                    <el-input
                      v-model="addressForms.billing.contact_name"
                      placeholder="请输入联系人"
                    />
                  </el-form-item>
                  <el-form-item label="联系电话" prop="contact_phone">
                    <el-input
                      v-model="addressForms.billing.contact_phone"
                      placeholder="请输入联系电话"
                    />
                  </el-form-item>
                  <el-form-item label="省市区" prop="geo_path">
                    <el-cascader
                      v-model="billingGeoPath"
                      :options="geoRegionOptions"
                      :props="{
                        value: 'value',
                        label: 'label',
                        children: 'children'
                      }"
                      filterable
                      placeholder="请选择省市区"
                      style="width: 100%"
                    />
                  </el-form-item>
                  <el-form-item label="详细地址" prop="address">
                    <el-input
                      v-model="addressForms.billing.address"
                      type="textarea"
                      :rows="2"
                      placeholder="请输入详细地址"
                    />
                  </el-form-item>
                  <el-form-item label="邮编">
                    <el-input
                      v-model="addressForms.billing.postal_code"
                      placeholder="请输入邮编"
                    />
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>

          <div class="form-actions">
            <el-button @click="activeStep = 1">上一步</el-button>
            <el-button
              type="primary"
              :loading="stepSubmitting.address"
              @click="submitAddresses"
            >
              保存并完成
            </el-button>
            <el-button link type="primary" @click="backToLogin">
              返回登录
            </el-button>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.verify-wrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 16px;
  background: linear-gradient(140deg, #f2f6ff 0%, #ffffff 100%);
}

.verify-card {
  width: 100%;
  max-width: 960px;
  padding: 24px 32px;
  border: none;
  box-shadow: 0 18px 42px rgb(48 86 178 / 14%);
}

.title {
  margin-bottom: 8px;
  font-size: 26px;
  font-weight: 600;
  color: #1f2937;
}

.subtitle {
  margin-bottom: 18px;
  color: #6b7280;
  line-height: 1.7;
}

.status-alert {
  margin-bottom: 18px;
}

.step-content {
  margin-top: 24px;
}

.form-block {
  margin-top: 16px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.license-upload {
  display: inline-block;
}

.license-preview {
  width: 260px;
  min-height: 160px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.license-preview img {
  max-width: 100%;
  max-height: 150px;
  object-fit: contain;
}

.preview-actions {
  margin-top: 8px;
  text-align: center;
}

.upload-drop {
  width: 260px;
  height: 160px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  background: #f9fafb;
  transition: all 0.3s ease;
  padding: 0 16px;
}

.upload-drop:hover {
  border-color: #3b82f6;
  color: #2563eb;
  background: #eef2ff;
}

.upload-plus {
  font-size: 36px;
  line-height: 1;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 14px;
  text-align: center;
}

.address-card {
  margin-top: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
